<template>
    <!-- <h3>专辑信息管理</h3> -->
    <div class="page-toggle">
        <div @click="addAlbumFn" :class="['toggle-button', { active: num == 0 }]">添加专辑</div>
        <span>|</span>
        <div @click="listSingerFn" :class="['toggle-button', { active: num == 1 }]">专辑列表</div>
    </div>
    <!-- 表单 -->
    <div class="singer-form" v-if="num == 0">

        <div class="opt">
            <el-input v-model="album.album_name" style="width: 360px; height: 44px; font-size: 16px"
                placeholder="专辑名称" />
        </div>

        <div class="opt" style="width: 360px;">
            <div>
                <el-input v-model="singerInput" style="width: 360px; height: 44px; font-size: 16px"
                    placeholder="请输入歌手" />
            </div>
            <el-select v-model="selectedValue" placeholder="请选择歌手">
                <el-option v-for="item in singers" :label="item.singer_name" :value="item.singer_id" />
            </el-select>
        </div>

        <div class="opt">
            <el-input v-model="album.description" type="textarea" style="width: 360px; font-size: 16px"
                placeholder="专辑介绍" />
        </div>

        <div class="opt">
            <span class="label">发布时间</span>
            <div class="block">
                <el-date-picker v-model="album.release_date" type="date" placeholder="请选择发布时间" size="default"
                    style="width: 360px; font-size: 16px" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
            </div>
        </div>

        <div class="opt">
            <span class="label">选择封面图片</span>
            <!-- 上传文件组件 -->
            <el-upload class="avatar-uploader" drag action="#" :on-change="chooseImageFn" :auto-upload="false"
                :show-file-list="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
            <div v-if="imageUrl" style="width: 178px; margin-top: 5px">
                <el-button @click="photoDeleteFn(imageUrl)" type="danger" plain>删除图片</el-button>
            </div>
        </div>

        <div class="opt">
            <el-button @click="addCategoryFn" type="primary" size="large">添加专辑</el-button>
        </div>
    </div>

    <!-- 表格 -->
    <div class="singer-table" v-if="num == 1">
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="index" label="序号" width="90" />
            <el-table-column prop="album_name" label="专辑名称" width="180" />
            <el-table-column prop="singer_id" label="歌手ID" width="180" />
            <el-table-column prop="release_date" label="发布日期" width="180" />
            <el-table-column label="封面图片" width="180">
                <template #default="scope">
                    <!-- scope.row.name -->
                    <img style="width: 60px;" v-if="scope.row.cover_image_url" :src="scope.row.cover_image_url" alt="">
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #header>
                    <el-input v-model="search" size="small" placeholder="搜索" />
                </template>
                <template #default="scope">
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 分页器 -->
    <div class="page" v-if="num == 1" >
        <!-- :page-count="page" -->
        <el-pagination :page-size="pageSize" :pager-count="pageSize" layout="prev, pager, next" :total="totalNum"
            @change="changePageFn" />
    </div>
</template>


<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { photoUpload, photoDelete, addAlbum, itemsAlbum, removeAlbum, searchSinger, searchAlbum } from '../../api/request'
import { ElMessage, ElMessageBox } from 'element-plus';
import type { Action } from 'element-plus'
import api from '../../api/index'
const imageUrl = ref('')
const pic = ref('')
const singerInput = ref('')
const num = ref(1)
const selectedValue = ref("")
// 专辑数量
let totalNum = ref(0)
let page = ref(1)
let pageSize = ref(9)
const search = ref('')
// 定义每一项数据的属性类型
// album_name, singer_id, release_date, cover_image_url, description
type Item = {
    singer_id: number
    index?: string | number,
    album_name: string
    release_date: string
    description: string
    picUrl: string
    cover_image_url: string
}
// 定义表单信息对象
const album = reactive({
    album_name: "",
    release_date: "",
    description: "",
    singer_id: ""
})

interface Singer {
    [key: string]: any
}
// 表格数据
const tableData = ref<any>([])

// 定歌手数组
const singers = ref<Singer>([])
let d: any = null;
watch(singerInput, (value: string) => {
    if (d != null) clearTimeout(d)
    d = setTimeout(() => {
        // console.log(value);
        // if(value == "") return ;
        searchSinger({ keyword: value })
            .then(
                content => {
                    // console.log(content)
                    let { result, code } = content;
                    if (code == 200) {
                        singers.value = result;
                        if (result) {
                            selectedValue.value = result[0].singer_name
                            album.singer_id = result[0].singer_id;
                        }
                    }
                }
            )
            .catch(err => console.log(err))
    }, 300)
})

watch(search, async (value: any) => {

    if (value == "") {
        getAlbumListFn();
    }
    else {
        // console.log(value);
        await searchAlbum({ keyword: value })
            .then(
                content => {
                    // console.log(content)
                    let { code, result, total } = content;
                    if (code == 200) {
                        // 整合后台数据
                        let arr = result.map((item: Item, index: number) => {
                            item.index = index + 1;
                            item.cover_image_url = api.url + item.cover_image_url
                            item.release_date = new Date(item.release_date).toLocaleDateString()
                            return item;
                        })
                        tableData.value = arr;
                        totalNum.value = total || 0;
                        // console.log({total})
                    }
                }
            )
    }
})
// 切换选项
const addAlbumFn = () => num.value = 0;
const listSingerFn = () => num.value = 1;

// 选择图标
const chooseImageFn = async (file: any) => {
    if (file) {
        // 创建表单实例
        let fd = new FormData()
        fd.append('photo', file.raw) // 把图片信息传递给服务器 ，服务器存储好图片，再返回一个图片路径
        // 调用上传图片的方法
        await photoUpload(fd)
            .then(
                content => {
                    console.log("图片路径:", content)
                    let { code, picUrl } = content;
                    if (code == 200) {
                        // 赋值（响应式）
                        imageUrl.value = api.url + picUrl;
                        pic.value = picUrl;
                    }
                    else {
                        ElMessage.error(content.msg);
                    }
                }
            )
    }

}
// 删除图片
const photoDeleteFn = async (picUrl: string) => {
    await photoDelete({ picUrl })
        .then(
            content => {
                console.log(content);
                let { code } = content;
                if (code == 200) {
                    // 重置图片路径
                    imageUrl.value = "";
                }
            }
        )
        .catch(err => console.log(err))
}
// 添加专辑
const addCategoryFn = async () => {
    let { album_name, release_date, description } = album;
    let singer_id = selectedValue.value;
    let cover_image_url = pic.value;
    // console.log(release_date)
    if (album_name == '' || release_date == '' || description == '') {
        ElMessage.error("缺少参数，请检查再提交");
        return false;
    }
    await addAlbum({ singer_id, album_name, release_date, description, cover_image_url })
        .then(
            content => {
                // console.log(content)
                let { code, msg } = content;
                // 添加分类名称成功
                if (code == 200) {
                    ElMessage.success(msg);
                    // 重置表单
                    album.album_name = ""
                    album.release_date = ""
                    album.description = ""
                    pic.value = "";
                    imageUrl.value = "";
                    selectedValue.value = "";
                    // 切换
                    num.value = 1;
                    // 重新获取列表
                    getAlbumListFn();
                }
                else {
                    ElMessage.error(msg)
                }
            }
        )
}

// 点击删除专辑
const handleDelete = (index: number, row: any) => {
    // console.log(index, row)
    // 获取当前点击的选项
    let { album_id, cover_image_url, album_name } = row;
    ElMessageBox.confirm(
        `是否删除这个“${album_name}”专辑?`,
        'Confirm',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(async () => {
            // console.log("点击确定")
            // 删除专辑
            await removeAlbum({ album_id })
                .then(
                    content => {
                        let { code, msg } = content;
                        if (code != 200) {
                            ElMessage.error(msg)
                        }
                    }
                )
            // 删除分类对应的图片
            console.log("-->", cover_image_url)
            await photoDelete({ picUrl: cover_image_url })
                .then(
                    content => {
                        // console.log(content);
                        let { code, msg } = content;
                        if (code != 200) {
                            ElMessage.error(msg)
                        }
                    }
                )
            // 删除程序中数组对应的数据
            tableData.value.splice(index, 1);
        })
        .catch((action: Action) => {
            // console.log("点击取消")
        })

}
// 获取专辑列表
const getAlbumListFn = async (page = 1, pageSize = 10) => {
    await itemsAlbum({ page, pageSize })
        .then(
            content => {
                // console.log(content)
                let { code, result, total } = content;
                if (code == 200) {
                    // 整合后台数据
                    let arr = result.map((item: Item, index: number) => {
                        item.index = index + 1;
                        item.cover_image_url = api.url + item.cover_image_url
                        item.release_date = new Date(item.release_date).toLocaleDateString()
                        return item;
                    })
                    tableData.value = arr;
                    totalNum.value = total;
                    // console.log({ total })
                }
            }
        )
}

// 点击分页时执行的函数
const changePageFn = (num: number) => {
    // console.log(value)
    page.value = num;
    getAlbumListFn(page.value, pageSize.value);
}
// 初始化
getAlbumListFn();

</script>

<style lang="scss">
@import '../../common/scss/common.scss';

.singer-form .opt,
.singer-table {
    margin-top: 15px;
}
.avatar-uploader-icon,
.el-upload-dragger,
.avatar-uploader,
.avatar {
    width: 128px;
    height: 128px;
    display: block;
    padding: 0 !important;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    text-align: center;
    padding: 0 !important;
    line-height: 128px;
}

.opt .label {
    color: #666;
    padding: 5px;
    margin-bottom: 5px;
    display: block;
}
</style>